package com.bootx.officialAccount.util;

import com.bootx.officialAccount.pojo.UploadImg;
import com.bootx.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.net.URL;

public class MediaUtils {

    private static final CloseableHttpClient HTTP_CLIENT = HttpClients.createDefault();

    public static UploadImg uploadimg(String accessToken, File file){
        String url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+accessToken;
        HttpPost uploadFile = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("media", file);
        HttpEntity multipart = builder.build();
        try {
            uploadFile.setEntity(multipart);
            CloseableHttpResponse response = HTTP_CLIENT.execute(uploadFile);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println(result);
            return JsonUtils.toObject(result, new TypeReference<UploadImg>() {});
        }catch (Exception e){
            UploadImg uploadImg = new UploadImg();
            uploadImg.setErrCode(1);
            uploadImg.setErrMsg(e.getMessage());
            return uploadImg;
        }
    }

    public static UploadImg uploadimg(String accessToken, String imageUrl){
        try {
            File file = new File("d:\\wechat_2025-08-09_135348_906.png");
            FileUtils.copyURLToFile(new URL(imageUrl),file);
            return uploadimg(accessToken,file);
        }catch (Exception e){
            UploadImg uploadImg = new UploadImg();
            uploadImg.setErrCode(1);
            uploadImg.setErrMsg(e.getMessage());
            return uploadImg;
        }
    }
}
